<template>
  <div>
    <!--添加按钮-->
    <el-button type="primary" icon="el-icon-plus" style="margin: 10px 0" @click="showDialog">添加</el-button>
    <!--表格组件
      data:表格需要展示的数据----数组类型
      以列展示
      type="index":显示序号
      prop:对应列的字段名
    -->
    <el-table :data="list" style="width: 100%" border>
      <el-table-column prop="date" type="index" label="序号" width="50" align="center"></el-table-column>
      <el-table-column prop="tmName" label="品牌名称" align="center"></el-table-column>
      <el-table-column prop="logoUrl" label="品牌LOGO" align="center">
        <template slot-scope="{row,$index}">
          <img :src="row.logoUrl" alt="" style="width: 100px;height: 100px">
        </template>
      </el-table-column>
      <el-table-column prop="address" label="操作" align="center">
        <template slot-scope="{row,$index}">
          <el-button type="warning" icon="el-icon-edit" size="mini" @click="updateTradeMark(row)">修改</el-button>
          <el-button type="warning" icon="el-icon-delete" size="mini" @click="deleteTradeMark(row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <!--
      分页器
      page-sizes:设置每页的展示的数据
      layout:实现分页器的布局
      pager-count:页码按钮数量 连续页码数=pager-count-2
      ->右边靠
    -->
    <el-pagination
      style="margin-top: 20px;text-align: center"
      @size-change="handleSizeChange"
      @current-change="getPageList"
      :current-page="page"
      :page-sizes="[3, 5, 10]"
      :page-size="limit"
      :pager-count="7"
      :total="total"
      layout="prev, pager, next, jumper, ->,total, sizes"
    >
    </el-pagination>
    <!--对话框 :visible.sync 控制对话框的显示与隐藏-->
    <el-dialog :title="tmForm.id?'修改品牌':'添加品牌'" :visible.sync="dialogFormVisible">
      <!--:model:收集表单数据,把表单的数据收集到tmForm对象上 也可用于表单验证-->
      <el-form ref="ruleForm" :model="tmForm" :rules="rules" style="width: 60%">
        <el-form-item prop="tmName" label="品牌名称" label-width="100px">
          <el-input autocomplete="off" v-model="tmForm.tmName"></el-input>
        </el-form-item>
        <el-form-item prop="logoUrl" label="品牌LOGO" label-width="100px">
          <!--图片上传 不能用v-model收集:不是表单元素-->
          <!--:on-success 当图片上传成功会执行 :before-upload 上传之前执行-->
          <el-upload
            class="avatar-uploader"
            action="/dev-api/admin/product/fileUpload"
            :show-file-list="false"
            :on-success="handleAvatarSuccess"
            :before-upload="beforeAvatarUpload"
            >
            <img v-if="tmForm.logoUrl" :src="tmForm.logoUrl" class="avatar">
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
            <div slot="tip" class="el-upload__tip">只能上传jpg/png文件，且不超过500kb</div>
          </el-upload>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="addOrUpdateTradeMark">确 定</el-button>
      </div>
    </el-dialog>

  </div>
</template>

<script>
export default {
  name: 'tradeMark',
  data() {
    return {
      page: 1,//当前页
      limit: 3,
      total: 0,//服务器返回的总条数
      list: [],//数据
      dialogFormVisible:false,//对话框的显示与隐藏
      imageUrl:'',//上传图片
      tmForm: { tmName:'', logoUrl:''},//收集品牌信息 对象的属性要与后端对应
      //表单验证规则
      /*
      * required:必须 前面会有星星*
      * trigger:什么时候校验 事件的设置(blur change)
      * */
      rules: {
        tmName: [
          { required: true, message: '请输入品牌名称', trigger: 'blur' },
          { min: 2, max: 6, message: '长度在 2 到 6 个字符', trigger: 'change' }
        ],
        logoUrl: [
          { required: true, message: '请选择品牌LOGO'}
        ]
      }
    }
  },
  mounted() {
    this.getPageList()
  },
  methods: {
    //获取品牌列表 pager= 1 是初赋始值
    async getPageList(pager = 1) {
      this.page = pager
      const { page, limit } = this
      let result = await this.$API.trademark.reqTradeMarkList(page, limit)
      if (result.code === 200) {
        this.total = result.data.total
        this.list = result.data.records
      }
    },
    //当每页的显示数量改变时
    handleSizeChange(limit) {
      this.limit = limit
      this.getPageList()
    },
    //单击事件显示对话框
    showDialog(){
      this.tmForm = { tmName:'', logoUrl:''}
      this.dialogFormVisible = true
    },
    //修改品牌 修改按钮 row:当前用户选中的信息(行)
    updateTradeMark(row){
      this.dialogFormVisible = true
      //将服务器返回的信息直接复制给tmForm
      this.tmForm = { ...row }//浅拷贝?
    },
    //添加或修改品牌 弹出对话框的 确定按钮
    addOrUpdateTradeMark(){
      //当全部验证字段通过
      this.$refs.ruleForm.validate(async (success)=>{
        if (success){
          try {
            let result = await this.$API.trademark.reqAddOrUpdateTradeMark(this.tmForm)
            if (result.code === 200){
              //弹出信息
              this.$message({
                type:'success',
                message:this.tmForm.id?"修改成功":"添加成功"
              })
              //关闭对话框
              this.dialogFormVisible = false
              //添加后留在第一页 修改后留在当前页
              await this.getPageList(this.tmForm.id?this.page:1)
            }
          }catch (e) {
            alert(e.message)
          }
        }else{
          alert('fail')
          return false
        }
      })
    },
    //删除
    deleteTradeMark(row){
      this.$confirm(`确定删除${row.tmName}吗?`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        let result = await this.$API.trademark.reqDeleteTradeMark(row.id)
        if (result.code === 200){
          this.$message({
            type: 'success',
            message: '删除成功!'
          });
          await this.getPageList(this.list.length>1?this.page:this.page-1)
        }
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        });
      });
    },
    //图片上传成功 res:图片上传成功之后返回的数据 file上传成功之后服务器返回前端数据
    handleAvatarSuccess(res, file) {
      this.tmForm.logoUrl = res.data
    },
    //图片上传之前
    beforeAvatarUpload(file) {
      const isJPG = file.type === 'image/jpeg';
      const isLt2M = file.size / 1024 / 1024 < 2;
      if (!isJPG) {
        this.$message.error('上传头像图片只能是 JPG 格式!');
      }
      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 2MB!');
      }
      return isJPG && isLt2M;
    },
  }
}
</script>

<style >
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #409EFF;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}
.avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>
